home *** CD-ROM | disk | FTP | other *** search
/ Amiga Format CD 43 / Amiga Format CD43 (1999)(Future Publishing)(GB)(Track 1 of 2)[!][issue 1999-09].iso / -serious- / programming / other / python-1.52 / lib / python1.5 / tempfile.py < prev    next >
Text File  |  1999-06-14  |  4KB  |  146 lines

  1. # Temporary file name allocation
  2. #
  3. # XXX This tries to be not UNIX specific, but I don't know beans about
  4. # how to choose a temp directory or filename on MS-DOS or other
  5. # systems so it may have to be changed...
  6.  
  7.  
  8. import os
  9.  
  10.  
  11. # Parameters that the caller may set to override the defaults
  12.  
  13. tempdir = None
  14. template = None
  15.  
  16.  
  17. # Function to calculate the directory to use
  18.  
  19. def gettempdir():
  20.     global tempdir
  21.     if tempdir is not None:
  22.         return tempdir
  23.     try:
  24.         pwd = os.getcwd()
  25.     except (AttributeError, os.error):
  26.         pwd = os.curdir
  27.     attempdirs = ['/usr/tmp', '/tmp', pwd]
  28.     if os.name == 'nt':
  29.         attempdirs.insert(0, 'C:\\TEMP')
  30.         attempdirs.insert(0, '\\TEMP')
  31.     elif os.name == 'amiga':
  32.         attempdirs.insert(0, 'SYS:T')
  33.         attempdirs.insert(0, ':T')
  34.         attempdirs.insert(0, 'T:')
  35.     elif os.name == 'mac':
  36.         import macfs, MACFS
  37.         try:
  38.              refnum, dirid = macfs.FindFolder(MACFS.kOnSystemDisk,
  39.                                               MACFS.kTemporaryFolderType, 1)
  40.              dirname = macfs.FSSpec((refnum, dirid, '')).as_pathname()
  41.              attempdirs.insert(0, dirname)
  42.         except macfs.error:
  43.             pass
  44.     for envname in 'TMPDIR', 'TEMP', 'TMP':
  45.         if os.environ.has_key(envname):
  46.             attempdirs.insert(0, os.environ[envname])
  47.     testfile = gettempprefix() + 'test'
  48.     for dir in attempdirs:
  49.         try:
  50.             filename = os.path.join(dir, testfile)
  51.             fp = open(filename, 'w')
  52.             fp.write('blat')
  53.             fp.close()
  54.             os.unlink(filename)
  55.             tempdir = dir
  56.             break
  57.         except IOError:
  58.             pass
  59.     if tempdir is None:
  60.         msg = "Can't find a usable temporary directory amongst " + `attempdirs`
  61.         raise IOError, msg
  62.     return tempdir
  63.  
  64.  
  65. # Function to calculate a prefix of the filename to use
  66.  
  67. _pid = None
  68.  
  69. def gettempprefix():
  70.     global template, _pid
  71.     if os.name == 'posix' and _pid and _pid != os.getpid():
  72.         # Our pid changed; we must have forked -- zap the template
  73.         template = None
  74.     if template is None:
  75.         if os.name == 'posix' or os.name=='amiga':
  76.             _pid = os.getpid()
  77.             template = '@' + `_pid` + '.'
  78.         elif os.name == 'nt':
  79.             template = '~' + `os.getpid()` + '-'
  80.         elif os.name == 'mac':
  81.             template = 'Python-Tmp-'
  82.         else:
  83.             template = 'tmp' # XXX might choose a better one
  84.     return template
  85.  
  86.  
  87. # Counter for generating unique names
  88.  
  89. counter = 0
  90.  
  91.  
  92. # User-callable function to return a unique temporary file name
  93.  
  94. def mktemp(suffix=""):
  95.     global counter
  96.     dir = gettempdir()
  97.     pre = gettempprefix()
  98.     while 1:
  99.         counter = counter + 1
  100.         file = os.path.join(dir, pre + `counter` + suffix)
  101.         if not os.path.exists(file):
  102.             return file
  103.  
  104.  
  105. class TemporaryFileWrapper:
  106.     """Temporary file wrapper
  107.  
  108.     This class provides a wrapper around files opened for temporary use.
  109.     In particular, it seeks to automatically remove the file when it is
  110.     no longer needed.
  111.     """
  112.     def __init__(self, file, path):
  113.         self.file = file
  114.         self.path = path
  115.  
  116.     def close(self):
  117.         self.file.close()
  118.         os.unlink(self.path)
  119.  
  120.     def __del__(self):
  121.         try: self.close()
  122.         except: pass
  123.  
  124.     def __getattr__(self, name):
  125.         file = self.__dict__['file']
  126.         a = getattr(file, name)
  127.         setattr(self, name, a)
  128.         return a
  129.  
  130.  
  131. def TemporaryFile(mode='w+b', bufsize=-1, suffix=""):
  132.     name = mktemp(suffix)
  133.     if os.name == 'posix':
  134.         # Unix -- be very careful
  135.         fd = os.open(name, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700)
  136.         try:
  137.             os.unlink(name)
  138.             return os.fdopen(fd, mode, bufsize)
  139.         except:
  140.             os.close(fd)
  141.             raise
  142.     else:
  143.         # Non-unix -- can't unlink file that's still open, use wrapper
  144.         file = open(name, mode, bufsize)
  145.         return TemporaryFileWrapper(file, name)
  146.